package com.sure0000.io;

import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketServer extends Thread {

    private ServerSocket server;

    public SocketServer() {
        try {
            // 监听指定的端口
            int port = 55533;
            server = new ServerSocket(port);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        System.out.println("server将一直等待连接的到来");
        while (!this.isInterrupted()) {
            try (
                    Socket socket = server.accept();
                    InputStream inputStream = socket.getInputStream();) {
                byte[] bytes = new byte[1024];
                int len;
                StringBuilder sb = new StringBuilder();
                while ((len = inputStream.read(bytes)) != -1) {
                    sb.append(new String(bytes, 0, len, "UTF-8"));
                }
                System.out.println("get message from client: " + sb);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public void closeSockect() {
        if (server != null && !server.isClosed()) {
            try {
                server.close();
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    public static void main(String[] args) throws Exception {
        SocketServer socketServer = new SocketServer();
        socketServer.start();
    }
}
